﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AyFrame.Dto;
using AyFrame.Strings;
using AyFrame.WebApi.Filters;

namespace AyFrame.WebApi.Controllers
{
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [ApiController]
    [ApiExceptionFilter]
    [Log]
    public abstract class BaseController : ControllerBase
    {
        [NonAction]
        public IActionResult Success(object data = null)
        {
            var obj = new InnerResponse
            {
                IsSuccess = true,
                Data = data
            };
            return Ok(obj);
        }

        [NonAction]
        public IActionResult Fail(string msg = null)
        {
            var obj = new InnerResponse
            {
                IsSuccess = false,
                Message = msg
            };
            return Ok(obj);
        }

        /// <summary>
        /// 获取请求头
        /// </summary>
        public IDictionary<string, string> Headers
        {
            get
            {
                var r = new Dictionary<string, string>();
                foreach (var h in Request.Headers)
                {
                    if (h.Key != "Authorization" || h.Key != "ApiKey") continue;
                    r.Add(h.Key, h.Value);
                }

                return r;
            }
        }

        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        public string UserId
        {
            get
            {
                var user = HttpContext.User;
                if (user == null || user.Identity == null || !user.Identity.IsAuthenticated) return null;

                var claims = user.Identity as ClaimsIdentity;
                var claim = claims.FindFirst(ClaimTypeString.UserId);

                return claim == null ? null : claim.Value;
            }
        }
    }
}
